<?php
Yii::import('widgets.tree.ZTreeWidget');

class ZTreeMenuWidget extends ZTreeWidget {

	public $menuItems;

	public function init() {
		parent::init();
		$route = $this->getController()->getRoute();
		$this->treeItems = $this->transformMenu($this->menuItems, $route);
	}
	protected function transformMenu($menuItems, $route) {
		$treeItems = array();
		foreach ($menuItems as $menuItem) {
			if (!isset($menuItem['visible']) || $menuItem['visible']) {
				$treeItems[] = $this->transformMenuItem($menuItem, $route);
			}
		}
		return $treeItems;
	}

	protected function transformMenuItem($menuItem, $route) {
		$treeItem = array();
		$treeItem['name'] = $menuItem['label'];
		if (!empty($menuItem['url'])) {
			$treeItem['url'] = $this->getController()
				->createUrl($menuItem['url'][0], array_splice($menuItem['url'], 1));
			$treeItem['active'] = $this->isItemActive($menuItem, $route);
		}
		$treeItem['target'] = '_self';
		if (!empty($menuItem['items'])) {
			$treeItem['childs'] = $this->transformMenu($menuItem['items'], $route);
			if (isset($treeItem['active']) && $treeItem['active']) {
				$treeItem['open'] = true;
			} else {
				foreach ($treeItem['childs'] as $child) {
					if (isset($child['active']) && $child['active']) {
						$treeItem['open'] = true;
						break;
					}
				}
			}
		}
		return $treeItem;
	}

	protected function isItemActive($item, $route) {
		if (isset($item['url']) && is_array($item['url'])
			&& !strcasecmp(trim($item['url'][0], '/'), $route)) {
			if (count($item['url']) > 1) {
				foreach (array_splice($item['url'], 1) as $name => $value) {
					if (!isset($_GET[$name]) || $_GET[$name] != $value)
						return false;
				}
			}
			return true;
		}
		return false;
	}
}
